package io.gitee.jinceon;

import io.gitee.jinceon.parser.CalculatorLexer;
import io.gitee.jinceon.parser.CalculatorParser;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;

public class Calculator {

    /**
     * 输入 1+2*3-4/5 之类的常量算式，返回计算结果
     * @param s 计算算式
     * @return
     */
    public static BigDecimal calculate(String s){
        return calculate(s, Collections.emptyMap());
    }

    /**
     * 输入 a+b*c-d/e 之类的带变量的算式，返回计算结果
     * @param s
     * @param context 变量上下文
     * @return
     */
    public static BigDecimal calculate(String s, Map<String, Number> context) {
        CharStream input = CharStreams.fromString(s);
        CalculatorParser parser = new CalculatorParser(new CommonTokenStream(new CalculatorLexer(input)));
        ParseTree tree = parser.prog();
        System.out.println(tree.toStringTree(parser));
        return new ExprVisitor(context).visit(tree);
    }

}
